#define _CRT_SECURE_NO_WARNINGS
#include<vector>
#include<string>
#include<iostream>
#include<queue>
using namespace std;

vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
	int n = quiet.size();
	vector <vector<int>> graph(n);
	vector<int> in(n, 0);
	for (auto& v : richer)
	{
		graph[v[0]].push_back(v[1]);
		in[v[1]]++;
	}
	queue<int> q;
	for (int i = 0; i < n; i++)
	{
		if (in[i] == 0)
			q.push(i);
	}
	vector<int> ret(n);
	for (int i = 0; i < n; i++)
		ret[i] = i;
	while (!q.empty())
	{
		auto tmp = q.front();
		q.pop();
		for (auto& e : graph[tmp])
		{
			if (quiet[ret[tmp]] < quiet[ret[e]])
				ret[e] = ret[tmp];
			in[e]--;
			if (in[e] == 0)
				q.push(e);
		}
	}
	return ret;
}
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
	vector<vector<int>> graph(n);
	vector<int> degree(n);
	for (auto& v : edges)
	{
		graph[v[0]].push_back(v[1]);
		graph[v[1]].push_back(v[0]);
		degree[v[0]]++;
		degree[v[1]]++;
	}
	queue<int> q;
	for (int i = 0; i < n; i++)
	{
		if (degree[i] == 1)
			q.push(i);
	}
	int remain = n;
	while (remain > 2)
	{
		int sz = q.size();
		remain -= sz;
		for (int i = 0; i < sz; i++)
		{
			auto tmp = q.front();
			q.pop();
			for (auto& e : graph[tmp])
			{
				degree[e]--;
				if (degree[e] == 1)
					q.push(e);
			}
		}
	}
	vector<int> ret;
	while (!q.empty())
	{
		ret.push_back(q.front());
		q.pop();
	}
	return ret;
}
int main()
{
	vector<vector<int>> richer = { {1,0},{2,1},{3,1},{3,7},{4,3},{5,3},{6,3} };
	vector<int> quiet = { 3,2,5,4,6,1,7,0 };
	loudAndRich(richer,quiet);
	return 0;
}